//
//  AppDelegate.m
//  TestAfn2
//
//  Created by xujingjing on 16/6/15.
//  Copyright © 2016年 xujingjing. All rights reserved.
//

#import "AppDelegate.h"
#import "BBLaunchAdMonitor.h"  //启动广告图(广告详情返回需要优化)
#import "XHLaunchAd.h"   //启动广告图

#import "TestViewController.h" //侧滑
// #import "VersionManage.h"   //版本更新  cocoapods安装



@interface AppDelegate ()
{

    BOOL isNeedShowBanner;

}
@property (nonatomic,strong)UITapGestureRecognizer * tap;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] init];
    self.window.rootViewController = [[TestViewController alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    
 //   [NSThread sleepForTimeInterval:5];
#pragma mark check netState
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
  
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"－－－－当前网络：未知－－－－－");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"－－－－当前网络：没有网络－－－－－");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"－－－－当前网络：3G|4G－－－－－");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"－－－－当前网络：WiFi－－－－－");
                break;
            default:
                break;
        }
        NSString *netState = [NSString stringWithFormat:@"%ld",status];

        [[NSNotificationCenter defaultCenter]postNotificationName:@"NETWORKSTATE" object:nil userInfo:@{@"netState":netState}];
        
        
    }];
    
    //set AFSecurityPolicy https
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    
    
    
    
    
    //set cache
//    NSURLCache *cache = [[NSURLCache alloc]initWithMemoryCapacity:2*1024*1024 diskCapacity:100*1024*1024 diskPath:nil];
//    [NSURLCache setSharedURLCache:cache];
//
    
    NSString *path = NSHomeDirectory();//主目录
    NSLog(@"NSHomeDirectory:%@",path);
    NSString *userName = NSUserName();//与上面相同
    NSString *rootPath = NSHomeDirectoryForUser(userName);
    NSLog(@"NSHomeDirectoryForUser:%@",rootPath);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"/cache"];//Documents目录
    NSLog(@"NSDocumentDirectory:%@",[NSString stringWithFormat:@"%@",documentsDirectory]);
    
    NSURLCache *urlCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
    [NSURLCache setSharedURLCache:urlCache];
    
    //read cache
    NSFileManager *fm = [NSFileManager defaultManager];
    [fm fileExistsAtPath:documentsDirectory];
    if([fm fileExistsAtPath:documentsDirectory]){//如果为真 证明有缓存路径
        //读取缓存数据
    }
    
    
   
//    //广告页
    [self requestLaunchImage];

    //    [self configDynamicStartPage];   //启动广告

    [self xhLaunchAD];//启动广告  也可以只要这一个方法实现
    
    
   //  [VersionManage checkVerSion];   // 版本更新
    
    
    return YES;
}

// 网络请求到banner图
-(void)requestLaunchImage{
    
    NSString *urlStr = [NSString stringWithFormat:@"http://jy.lekeup.com/app/index/getStartpage"];
    [TestAfnetHttp postWithUrl:urlStr paramters:nil success:^(id response) {
        
        NSString *message = response[@"result_data"][@"message"];
        NSLog(@"%@",message);
        NSString *path = response[@"result_data"][@"startpage"];;
//保存下来
        [[NSUserDefaults standardUserDefaults] setObject:path forKey:Adver_LaunchScreen];


        
    } failed:^(id error) {
        
        
    }];
    
    
    
}

#pragma mark -- 配置动态启动页

-(void)configDynamicStartPage{
 //获取缓存路径
    NSString *path = [[NSUserDefaults standardUserDefaults] objectForKey:Adver_LaunchScreen];

    // 接收点击“跳过”通知
   // [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showAdDetail:) name:BBLaunchAdDetailDisplayNotification object:nil];
    
    [BBLaunchAdMonitor showAdAtPath:path
                             onView:self.window.rootViewController.view
                       timeInterval:5.
                   detailParameters:@{@"carId":@(12345), @"name":@"奥迪-品质生活"}];//@"carId":@(12345), @"name":@"奥迪-品质生活"

    
    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isNeedShowBanner"];

        self.window.rootViewController.view.userInteractionEnabled = YES;
        [self.window.rootViewController.view addGestureRecognizer:self.tap];



    
}


-(UITapGestureRecognizer *)tap{
    if (!_tap) {
        
        _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showAdDetailZH)];
        
        
    }
    return _tap;
}
//跳过启动页广告
- (void)showAdDetail:(NSNotification *)noti{
    
    NSLog(@"detail parameters:%@", noti.object);
 
    [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"isNeedShowBanner"];
    
}
//点击了跳转广告详情
- (void)showAdDetailZH{
    
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isNeedShowBanner"]) {
        return;
    }
  //  [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://jy.lekeup.com/app/index/getSetup" ]];
    [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"isNeedShowBanner"];
    [self.window.rootViewController.view removeGestureRecognizer:_tap];
}


#pragma mark xhLaunchAD
- (void)xhLaunchAD{

    //1.初始化启动页广告(初始化后,自动添加至视图,不用手动添加)
    XHLaunchAd *launchAd = [[XHLaunchAd alloc] initWithFrame:CGRectMake(0, 0,self.window.bounds.size.width,  self.window.bounds.size.height-150) andDuration:2];
    
    //2.设置启动页广告图片的url(必须)
    NSString *imgUrlString =@"http://img.taopic.com/uploads/allimg/120906/219077-120Z616330677.jpg";
    
    [launchAd imgUrlString:imgUrlString options:XHWebImageRefreshCached completed:^(UIImage *image, NSURL *url) {
        //异步加载图片完成回调(若需根据图片实际尺寸,刷新广告frame,可在这里操作)
        //launchAd.adFrame = ...;
    }];
    
    //是否影藏'倒计时/跳过'按钮[默认显示](可选)
    launchAd.hideSkip = NO;
    
    //广告点击事件(可选)
    launchAd.clickBlock = ^()
    {
        NSString *url = @"http://jy.lekeup.com/app/index/getSetup";
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    };


}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
